<script setup lang="ts">
import YkPagination from '@yk/components/pagination/YkPagination.vue'
import { Pages } from '@typings/pages'
import { Download } from '@element-plus/icons-vue'
import YkTableColumn from '@yk/components/table-column/YkTableColumn.vue'
import { ObjectUtil } from '@utils/object-util'
import { ElForm } from 'element-plus'
import YkDatePicker from '@yk/components/date-picker/YkDatePicker.vue'
import AlarmAnalysis from '@views/alarm/components/AlarmAnalysis.vue'
import { TableUtil } from '@utils/table-util'
import { alarmBecomeSilentAPI, getAlarmListByPageAPI, getAlarmStatisticsAPI } from '@/api/alarm'
import { AlarmHistoryDTO, AlarmStatisticsVO } from '@/api/entity/alarm'
import { DeviceDTO } from '@/api/entity/device'
import { getDeviceListAPI } from '@/api/device'
import { getVariableListByDeviceIdAPI } from '@/api/variable'
import { VariableDTO } from '@/api/entity/variable'
import { AlarmUtil, MountedCheck } from '@/utils'
import { DeviceRoleUtil } from '@/dataset/device-role'
import { TabBarUtil } from '@/layout/components/tab-bar'

defineOptions({ name: 'AlarmReport' })

const mc = new MountedCheck()
onMounted(() => {
  DeviceRoleUtil.updateRole()
  searchHandle()
  getAlarmStatistics()
  getDeviceList()
  mc.end()
})

onActivated(() => {
  if (mc.isMounted()) return
  DeviceRoleUtil.updateRole()
  getAlarmStatistics()
  getTableData()
})

// region TODO 查询
const searchParams = reactive({
  // 状态 false-正常
  alarmState: null as boolean,
  // 设备id
  deviceId: '',
  // 结束时间
  endTime: '',
  // 开始时间
  startTime: '',
  // 变量id
  variableId: ''
})
function searchHandle () {
  pages.pageNum = 1
  exportParams.value = ObjectUtil.copy(searchParams)
  getTableData()
}
// endregion

// region TODO 设备列表
const deviceList = shallowRef<DeviceDTO[]>(null)
function getDeviceList () {
  getDeviceListAPI().then((res) => {
    res.result().then((rdata) => {
      deviceList.value = rdata.data
    })
  })
}
// 设备 - Change
function deviceChangeHandle () {
  if (searchParams.deviceId) {
    getVariableList()
  } else {
    variableList.value = []
  }
}
// endregion

// region TODO 变量列表
const variableList = shallowRef<VariableDTO[]>(null)
function getVariableList () {
  getVariableListByDeviceIdAPI({ id: searchParams.deviceId }).then((res) => {
    res.result().then((rdata) => {
      variableList.value = rdata.data
    })
  })
}
watch(() => searchParams.deviceId, (nv) => {
  searchParams.variableId = ''
  if (nv) {
    getVariableList()
  } else {
    variableList.value = []
  }
})
// endregion

// region TODO 统计数据
const alarmStatistics = shallowRef<AlarmStatisticsVO>({
  // 今日报警中
  todayAlarmCount: 0,
  // 今日报警数
  todayCount: 0,
  // 今日已恢复
  todayRecoverCount: 0,
  // 本周报警数
  weekCount: 0
})
function getAlarmStatistics () {
  getAlarmStatisticsAPI().then((res) => {
    res.result().then((rdata) => {
      alarmStatistics.value = rdata.data
    })
  })
}
// endregion

// region TODO 表格数据
const pages = reactive(new Pages())
const tableData = ref<AlarmHistoryDTO[]>([])
function getTableData () {
  const loading = ElLoading.service()
  getAlarmListByPageAPI({
    ...pages.getParams(),
    param: searchParams
  }).then((res) => {
    res.result().then((rdata) => {
      tableData.value = rdata.records || []
      pages.total = rdata.total
    })
  }).finally(loading.close)
}

// endregion

// region TODO 消音
function alarmErasure (item: AlarmHistoryDTO) {
  const loading = ElLoading.service()
  alarmBecomeSilentAPI({ id: item.id, status: true }).then((res) => {
    res.result().then(() => {
      ElMessage.success('报警已消音')
      item.status = true
    })
  }).finally(loading.close)
}
// endregion

// region TODO 导出
const exportParams = shallowRef<typeof searchParams>()
// endregion

// region TODO 报警分析
// 对话框
const alarmAnalysisModel = ref(false)
// 报警分析 - 报警数据
const alarmAnalysisData = ref<AlarmHistoryDTO>()
function showAlarmAnalysis (data: AlarmHistoryDTO) {
  alarmAnalysisData.value = data
  alarmAnalysisModel.value = true
}
function closeAlarmAnalysis () {
  alarmAnalysisModel.value = false
}
// endregion

// region TODO 跳转
// 报警规则
function toAlarmRule (id: string) {
  TabBarUtil.value.reopen({ name: 'AlarmRule', params: { id } })
}
// endregion
</script>

<template>
  <div class="layout_view d-flex flex-column" style="min-height: 100%">
    <!--统计-->
    <div class="c_card-white d-flex statistics" style="height: 136px">
      <div class="statistics__item flex-1">
        <div class="title">今日报警数</div>
        <div class="value">{{ alarmStatistics.todayCount }}<span class="unit">项</span></div>
      </div>
      <div class="statistics__item flex-1 ml-12">
        <div class="title">今日报警中</div>
        <div class="value">{{ alarmStatistics.todayAlarmCount }}<span class="unit">项</span></div>
      </div>
      <div class="statistics__item flex-1 ml-12">
        <div class="title">今日已恢复</div>
        <div class="value">{{ alarmStatistics.todayRecoverCount }}<span class="unit">项</span></div>
      </div>
      <div class="statistics__item flex-1 ml-12">
        <div class="title">本周报警数</div>
        <div class="value">{{ alarmStatistics.weekCount }}<span class="unit">项</span></div>
      </div>
    </div>
    <!--报警数据-->
    <div class="c_card-page w-100 flex-1 mt-12">
      <div class="c_card_header c_card-title bor-divider-b">报警数据</div>
      <!--搜索表单-->
      <el-form inline class="c_form-search mt-3">
        <el-form-item label="触发器名称：">
          <el-select
            v-model="searchParams.deviceId" placeholder="全部设备" clearable
            filterable
            @change="deviceChangeHandle"
          >
            <el-option value="">全部</el-option>
            <el-option
              v-for="item in deviceList" :key="item.id" clearable
              :label="item.deviceName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchParams.variableId" placeholder="全部变量" filterable>
            <el-option value="">全部</el-option>
            <el-option v-for="item in variableList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchParams.alarmState" placeholder="全部状态" clearable>
            <el-option label="正常" :value="false" />
            <el-option label="报警" :value="true" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <yk-date-picker
            v-model:start="searchParams.startTime" v-model:end="searchParams.endTime" :days="30"
            :default-date="6" value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchHandle">查询</el-button>
        </el-form-item>
        <el-form-item class="float-right mr-0">
          <export-file url="/alarmHistory/export" :params="exportParams">
            <el-button class="c_btn--export" :icon="Download as any">导出</el-button>
          </export-file>
        </el-form-item>
      </el-form>
      <!--表格-->
      <el-table class="c_table-page w-100" stripe :data="tableData">
        <el-table-column label="#" type="index" :index="TableUtil.indexMethod.bind(this, pages)" />
        <yk-table-column label="状态" prop="">
          <template #default="scope">
            <el-tag v-if="scope.row.alarmState" type="danger" effect="dark" size="small">报警</el-tag>
            <el-tag v-else type="success" effect="dark" size="small">正常</el-tag>
          </template>
        </yk-table-column>
        <yk-table-column label="设备名称" prop="deviceName" />
        <yk-table-column label="变量" prop="variableName" />
        <yk-table-column label="报警值" prop="alarmValue" />
        <yk-table-column label="触发条件">
          <template #default="scope">{{ AlarmUtil.formatCondition(scope.row.rule) }}</template>
        </yk-table-column>
        <yk-table-column label="报警时间" prop="alarmAt" />
        <yk-table-column label="恢复时间" prop="recoverAt" />
        <el-table-column label="操作" width="220px">
          <template #default="scope">
            <div class="c_table-operation">
              <el-link type="primary" size="small" @click="showAlarmAnalysis(scope.row)">故障分析</el-link>
              <el-link
                v-if="DeviceRoleUtil.isAdmin(scope.row.deviceId)" type="primary" size="small"
                @click="toAlarmRule(scope.row.alarmId)"
              >
                报警设置
              </el-link>
              <template v-if="scope.row.alarmState && DeviceRoleUtil.isManager(scope.row.deviceId)">
                <el-link
                  v-if="!scope.row.status" type="danger"
                  size="small"
                  @click="alarmErasure(scope.row)"
                >
                  消音
                </el-link>
                <span v-else class="ml-16 color-secondary">已消音</span>
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <el-affix target=".c_table-page" position="bottom" :offset="0">
        <yk-pagination class="c_table-pagination-page" :pages="pages" @handle="getTableData" />
      </el-affix>
    </div>
    <!--报警分析-->
    <el-dialog
      v-model="alarmAnalysisModel" title="报警分析" width="800px"
      :close-on-click-modal="false" draggable :modal="false"
      @close="closeAlarmAnalysis"
    >
      <alarm-analysis :alarm="alarmAnalysisData" />
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
// 统计
.statistics {
  .statistics__item {
    padding: 27px 0 0 18px;
    background: #F7F8FA url("@images/card/card-decorate-down.png") right bottom no-repeat;
    .title {
      font-size: 14px;
      color: var(--el-text-color-primary);
    }
    .value {
      font-size: 24px;
      color: var(--yk-color-primary);
      margin-top: 4px;
      font-weight: bold;
    }
    .unit {
      font-size: 12px;
      font-weight: normal;
      margin-left: 4px;
    }
  }
}
</style>
